/** 2. 搜索条件提取脚本 */
<template>
  <div class="editor_container">
    <div class="code-container">
      <div class="script-header">
        <a-button type="primary" :loading="updateLoading" @click="save_script"
          >更新脚本</a-button
        >
      </div>
      <MonacoEditor
        editorId="siteConditionEditor"
        ref="siteConditionEditor"
        v-model="script_code"
      />
    </div>
    <div class="result-container">
      <div class="result-header">
        <div>
          加载搜索条件:
          <a-select
            style="width: 128px"
            placeholder="请选择类目"
            v-model:value="selectedCategory"
            :options="category_options"
          />
        </div>
        <!-- <a-button @click="save_script">
          <RocketOutlined />
          保存脚本
        </a-button> -->
        <a-button type="primary" @click="execute">
          <RocketOutlined />
          执行
        </a-button>
      </div>
      <div class="script-body">
        <MonacoEditor
          editorId="siteConditionResultEditor"
          v-model="result_code"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineExpose, defineProps } from "vue";
import {
  get_site_script_data,
  update_site_script_data,
} from "@/utils/storage.js";
import { script_execute } from "@/api/script";
import { message } from "ant-design-vue";

const props = defineProps({
  current_site: {
    type: String,
    default: "",
  },
  tab_data: {
    type: Object,
    default: () => {},
  },
});

const script_id = ref(-1);
const script_code = ref('print("Hello World!")');
const result_code = ref("{}");
const category_options = ref([]);
const selectedCategory = ref(null);
const updateLoading = ref(false);

// 执行脚本
const execute = async () => {
  if (script_id.value === -1) {
    message.error("获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试");
    return;
  }
  try {
    let res = await script_execute(script_id.value, [
      {
        dataType: "string",
        name: "website_code",
        paramId: "",
        paramType: 1,
        value: props.current_site,
      },
      {
        dataType: "int",
        name: "category_id",
        paramId: "",
        paramType: 1,
        value: selectedCategory.value,
      },
    ]);
    console.log("execute script result ->", res);
    let format_result = JSON.stringify(JSON.parse(res.data), null, 2);
    result_code.value = format_result;
  } catch (err) {
    message.error("执行脚本时发生错误");
    console.error("execute script error ->", err);
  }
};

// 保存脚本
const save_script = async () => {
  // 获取当前脚本
  let script = (await get_site_script_data(props.current_site))?.scripts?.find(
    (item) => item.description === "CONDITION_EXTRACT"
  );
  if (script) {
    script.content = script_code.value;
    updateLoading.value = true;
    // 更新脚本
    await update_site_script_data(props.current_site, script);
    message.success("保存脚本成功");
    updateLoading.value = false;
  } else {
    message.error("获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试");
  }
};

const reload = async () => {
  if (!props.current_site) {
    return;
  }
  // 读取上次脚本运行结果
  let category_result = localStorage.getItem(
    `${props.current_site}-siteCategoryResult`
  );
  if (category_result) {
    category_options.value = JSON.parse(category_result);
    // 设置 label 和 value
    category_options.value.forEach((item) => {
      item.label = item.category_name;
      item.value = `${item.id}`;
    });
  }

  // 获取当前脚本
  let script = (await get_site_script_data(props.current_site))?.scripts?.find(
    (item) => item.description === "CONDITION_EXTRACT"
  );
  if (script) {
    script_id.value = script.id;
    script_code.value = script.content;
  } else {
    script_id.value = -1;
    script_code.value = "# 请从左侧的站点列表选择需要处理的站点";
    message.error("获取脚本信息失败，请手动保存修改后的脚本再刷新页面重试");
  }
};

onMounted(() => {
  reload();
});

defineExpose({
  reload,
});
</script>

<script>
import MonacoEditor from "@/components/commons/MonacoEditor.vue";
import { Button, Select } from "ant-design-vue";
import { RocketOutlined } from "@ant-design/icons-vue";

export default {
  name: "SetConditionScript",
  components: {
    MonacoEditor,
    ASelect: Select,
    AButton: Button,
    RocketOutlined,
  },
};
</script>

<style lang="scss" scoped>
.editor_container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: flex-start;

  .code-container {
    height: 100%;
    width: 52%;
    display: flex;
    flex-direction: column;
  }

  .script-header {
    height: 50px;
    display: flex;
    align-items: center;
  }

  .script-body {
    flex: 1;
    width: 100%;
    min-height: 0;
  }

  .result-container {
    width: 46%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .result-header {
      height: 50px;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      border-bottom: 1px solid #e8e8e8;
    }
  }
}
</style>
